import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Table, 
  Button, 
  Typography, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select,
  message,
  Alert,
  Tooltip,
  Popconfirm
} from 'antd';
import { 
  KeyOutlined, 
  PlusOutlined, 
  EyeOutlined, 
  EyeInvisibleOutlined,
  CopyOutlined,
  DeleteOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;
const { Option } = Select;

interface APIKey {
  id: string;
  name: string;
  provider: string;
  access_key: string;
  secret_key: string;
  status: 'active' | 'disabled';
  created_at: string;
  last_used: string | null;
  description?: string;
}

const AKSKSettings: React.FC = () => {
  const [apiKeys, setApiKeys] = useState<APIKey[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [visibleSecrets, setVisibleSecrets] = useState<Set<string>>(new Set());
  const [form] = Form.useForm();

  // 模拟数据
  useEffect(() => {
    setApiKeys([
      {
        id: '1',
        name: '生产环境密钥',
        provider: 'aliyun',
        access_key: 'AK_20240115_001',
        secret_key: 'SK_20240115_001_abcd1234efgh5678',
        status: 'active',
        created_at: '2024-01-15',
        last_used: '2024-01-20',
        description: '用于生产环境API调用'
      },
      {
        id: '2',
        name: '测试环境密钥',
        provider: 'tencent',
        access_key: 'AK_20240110_002',
        secret_key: 'SK_20240110_002_wxyz9876mnop5432',
        status: 'disabled',
        created_at: '2024-01-10',
        last_used: null,
        description: '用于开发测试环境'
      }
    ]);
  }, []);

  const toggleSecretVisibility = (keyId: string) => {
    const newVisibleSecrets = new Set(visibleSecrets);
    if (newVisibleSecrets.has(keyId)) {
      newVisibleSecrets.delete(keyId);
    } else {
      newVisibleSecrets.add(keyId);
    }
    setVisibleSecrets(newVisibleSecrets);
  };

  const copyToClipboard = (text: string, type: string) => {
    navigator.clipboard.writeText(text).then(() => {
      message.success(`${type}已复制到剪贴板`);
    }).catch(() => {
      message.error('复制失败');
    });
  };

  const handleCreate = async (values: any) => {
    try {
      setIsLoading(true);
      setError(null);
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const newKey: APIKey = {
        id: Date.now().toString(),
        name: values.name,
        provider: values.provider,
        access_key: `AK_${new Date().toISOString().slice(0, 10).replace(/-/g, '')}_${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`,
        secret_key: `SK_${new Date().toISOString().slice(0, 10).replace(/-/g, '')}_${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}_${Math.random().toString(36).substring(2, 18)}`,
        status: 'active',
        created_at: new Date().toISOString().slice(0, 10),
        last_used: null,
        description: values.description
      };
      
      setApiKeys(prev => [newKey, ...prev]);
      message.success('API密钥创建成功');
      setModalVisible(false);
      form.resetFields();
      
      // 显示新创建的密钥
      setVisibleSecrets(new Set([newKey.id]));
      
    } catch (error: any) {
      setError(error.message || '创建失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const handleDelete = async (keyId: string) => {
    try {
      setIsLoading(true);
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      setApiKeys(prev => prev.filter(key => key.id !== keyId));
      message.success('API密钥删除成功');
    } catch (error) {
      message.error('删除失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const handleStatusChange = async (keyId: string, newStatus: 'active' | 'disabled') => {
    try {
      setIsLoading(true);
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      setApiKeys(prev => prev.map(key => 
        key.id === keyId ? { ...key, status: newStatus } : key
      ));
      message.success(`密钥已${newStatus === 'active' ? '启用' : '禁用'}`);
    } catch (error) {
      message.error('操作失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN');
  };

  const getProviderLabel = (provider: string) => {
    const providerMap: Record<string, string> = {
      'aliyun': '阿里云',
      'tencent': '腾讯云',
      'volcengine': '火山云'
    };
    return providerMap[provider] || provider;
  };

  const columns: ColumnsType<APIKey> = [
    {
      title: '密钥信息',
      key: 'keyInfo',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: '4px' }}>{record.name}</div>
          <div style={{ marginBottom: '4px' }}>
            <Tag color="blue">{getProviderLabel(record.provider)}</Tag>
          </div>
          <Text type="secondary" style={{ fontSize: '12px' }}>
            {record.description || '无描述'}
          </Text>
        </div>
      ),
    },
    {
      title: 'Access Key',
      dataIndex: 'access_key',
      key: 'access_key',
      render: (accessKey: string) => (
        <Space>
          <Text code style={{ fontSize: '12px' }}>{accessKey}</Text>
          <Tooltip title="复制">
            <Button 
              type="text" 
              size="small" 
              icon={<CopyOutlined />}
              onClick={() => copyToClipboard(accessKey, 'Access Key')}
            />
          </Tooltip>
        </Space>
      ),
    },
    {
      title: 'Secret Key',
      key: 'secret_key',
      render: (_, record) => {
        const isVisible = visibleSecrets.has(record.id);
        const displayKey = isVisible ? record.secret_key : '••••••••••••••••••••';
        
        return (
          <Space>
            <Text code style={{ fontSize: '12px' }}>{displayKey}</Text>
            <Tooltip title={isVisible ? "隐藏" : "显示"}>
              <Button 
                type="text" 
                size="small"
                icon={isVisible ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                onClick={() => toggleSecretVisibility(record.id)}
              />
            </Tooltip>
            {isVisible && (
              <Tooltip title="复制">
                <Button 
                  type="text" 
                  size="small" 
                  icon={<CopyOutlined />}
                  onClick={() => copyToClipboard(record.secret_key, 'Secret Key')}
                />
              </Tooltip>
            )}
          </Space>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: 'active' | 'disabled') => (
        <Tag color={status === 'active' ? 'success' : 'default'}>
          {status === 'active' ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (date: string) => formatDate(date),
      sorter: (a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
    },
    {
      title: '最后使用',
      dataIndex: 'last_used',
      key: 'last_used',
      render: (date: string | null) => date ? formatDate(date) : '未使用',
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            onClick={() => handleStatusChange(record.id, record.status === 'active' ? 'disabled' : 'active')}
          >
            {record.status === 'active' ? '禁用' : '启用'}
          </Button>
          <Popconfirm
            title="确认删除"
            description="删除后无法恢复，确定要删除这个API密钥吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题 */}
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'flex-start',
        marginBottom: '24px'
      }}>
        <div>
          <Title level={2} style={{ margin: 0, marginBottom: '8px' }}>
            <KeyOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
            API密钥管理
          </Title>
          <Text type="secondary">管理用于API访问的Access Key和Secret Key</Text>
        </div>
        <Button 
          type="primary" 
          size="large"
          icon={<PlusOutlined />}
          onClick={() => setModalVisible(true)}
        >
          创建密钥
        </Button>
      </div>

      {/* 使用说明 */}
      <Alert
        message="安全提示"
        description="请妥善保管您的API密钥，不要在代码中硬编码或分享给他人。建议定期轮换密钥以确保安全。"
        type="warning"
        showIcon
        style={{ marginBottom: '24px' }}
      />

      {/* API密钥列表 */}
      <Card>
        <Table
          columns={columns}
          dataSource={apiKeys}
          rowKey="id"
          loading={isLoading}
          pagination={{
            total: apiKeys.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
        />
      </Card>

      {/* 创建密钥模态框 */}
      <Modal
        title="创建API密钥"
        open={modalVisible}
        onCancel={() => {
          setModalVisible(false);
          setError(null);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        confirmLoading={isLoading}
        width={600}
      >
        {error && (
          <Alert
            message={error}
            type="error"
            showIcon
            closable
            onClose={() => setError(null)}
            style={{ marginBottom: '16px' }}
          />
        )}
        
        <Form
          form={form}
          layout="vertical"
          onFinish={handleCreate}
        >
          <Form.Item
            name="provider"
            label="云服务商"
            rules={[{ required: true, message: '请选择云服务商' }]}
          >
            <Select placeholder="选择云服务商">
              <Option value="aliyun">阿里云</Option>
              <Option value="tencent">腾讯云</Option>
              <Option value="volcengine">火山云</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="name"
            label="密钥名称"
            rules={[
              { required: true, message: '请输入密钥名称' },
              { max: 50, message: '名称长度不能超过50个字符' }
            ]}
          >
            <Input placeholder="例如：生产环境密钥" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
            rules={[
              { max: 200, message: '描述长度不能超过200个字符' }
            ]}
          >
            <Input.TextArea 
              rows={3}
              placeholder="描述这个密钥的用途（可选）"
            />
          </Form.Item>
        </Form>

        <Alert
          message="注意事项"
          description="创建后请立即保存Secret Key，系统不会再次显示完整的Secret Key。"
          type="info"
          showIcon
          style={{ marginTop: '16px' }}
        />
      </Modal>
    </div>
  );
};

export default AKSKSettings; 